<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="utf-8" />
  <meta name="referrer" content="never">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=device-dpi" />
  <title>上传视频</title>
  <link rel="stylesheet" type="text/css" href="./css/updatePage.css" >
  <script type="text/javascript" src="./js/jquery-1.11.3.min.js"></script>
  <script type="text/javascript" src="./js/vue.js"></script>
  <script type="text/javascript" src="./js/webuploader.js"></script>
  <script type="text/javascript" src="./js/md5.js"></script>
  <script type="text/javascript" src="./js/upload.js"></script>
  <script type="text/javascript" src="./js/uploadFm.js"></script>
  <script type="text/javascript" src="./js/error.js"></script>
</head>

<body>
   <!--上传按钮-->
   <div id="updatePage">
	  <div class="title">发布</div>
      <div class="list">
      		<div class="wb">
      			上传作品
      		</div>
			  <div id="chosevideo" class="webuploader-container listRight">
				<div id="showToast">
					  +上传作品
					<!--  <div id="jindu"></div>
					  <div id="jinduwb">+上传视频</div> -->
				</div>
				 <!-- <div id="rt_rt_1e4foqijm117l5dc1851dehgkh1">
					<input type="file" name="file" class="webuploader-element-invisible" />
				  </div> -->
	        </div>
      </div>
      <div class="list" @click="handlerFm">
      	<div class="wb">选择封面</div>
      	<div id="chosefm" class="listRight">
			<div class="bgwb"
				:class="choiceFm ? 'isFmed' : '' "
				:style="{'background-image' : 'url(' + tempFmSrc + ')'}">
				选择封面
			</div>
		</div>
      </div>
      
      <div class="iconContent">
      	<div class="iconTitle">标题</div>
      	<textarea :placeholder="placeholder" maxlength="140" v-model="title" @focus="placeholder = ''" @blur="placeholder = '写标题并使用合适的类型，能让更多人看到喔~'"></textarea>
      	<div class="length-tips">{{title.length}}/140</div>
		<div class="iconList">
			<div class="listClass" @click="setTitle({id: 1, name: ''})"># 标签</div>
      		<div class="listClass" v-for="item in hotType" @click="setTitle(item)"># {{item.name}}</div>
      	</div>
      </div>
      
      <button id="send"  class="send"  @click="sendVideo" disabled="true">
			发布
	  </button>
      
   </div>
   
  <!--/上传按钮-->
</body>
</html>

<script language="javascript">
    // 分割下地址栏参数
	var request = new Object(),
		// 第三方的
		ServerUrl = '',
		token = '',
		// 接口地址
		requestUrl = '',
		// 上传后接收视频ID
		saveVideoId = '',
		// 封面ID
		saveFmId = '',
		// 允许修改封面
		saveFmIdChange = 0,
		// 视频标题
		tempTitle = '',
		// 组织视频重复上传
		testTemp = null;
		// 获取进度，视频未传完之前 禁止点击封面
		isDisabedFm = false,
		// 虚拟进度
		tempJinDu = 1;
	if(location.search) localStorage.setItem('hybridInfo', location.search)
	function splitAddressUrl(){
		  var url = localStorage.getItem('hybridInfo');
		 if (url.indexOf("?") != -1) {
		   var str = url.substr(1);
		   strs = str.split("&");
			for(var i = 0; i < strs.length; i ++) {
			  if (strs[i].indexOf('token') >= 0) {
				  request[strs[i].split("=")[0]] = (strs[i].split("=")[1]).replace('%20', ' ');
			  }else {
				  request[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
			  }
			}
		 }
	};
	
	// 储存视频的函数
	function setSaveVideo(ppvod_id) {
		$.ajax({
			url: requestUrl + '/user/upload/create',
			type: "post",
			dataType: "json",
			headers: {
				"Authorization": token
			},
			data: {
				"ppvod_video_id": ppvod_id,
				"type": 2
			},
			success: function(r) {
				if (r.status == 0) {
					saveVideoId = r.data.id;
					// 允许点击发布按钮
					$('#send').attr('disabled', false);
					$('#send').css({'background-color': '#E62D54', 'color': 'white'});
				}else {
					showDalogleInfo({'text': r.msg, 'time': 2000});
					setTimeout(function(){
						window.location.reload();
					}, 2000);
				}
			},
			error: function(e) {
			}
		});
	};
	
	// 用户不重新选择封面 向 数据库储存封面的函数
	function setSaveFm(ppvod_id) {
		$.ajax({
			url: requestUrl + '/user/upload/create',
			type: "post",
			dataType: "json",
			headers: {
				"Authorization": token
			},
			data: {
				"ppvod_video_thumb_id": ppvod_id,
				"type": 3
			},
			success: function(r) {
				if(r.status == 0) {
					saveFmId = r.data.id;
				}else {
					showDalogleInfo({'text': r.msg, 'time': 2000});
					setTimeout(function(){
						window.location.reload();
					}, 2000);
				}
			},
			error: function(e) {
			}
		});
	};
	
	// 测试背景图片是否可ping
	function pingBgUrl(url, tempVideoId) {
		var setPingTime = null;
		clearInterval(setPingTime);
		setPingTime =  setInterval(function(){
			$.ajax({
			       type: "GET",
			       cache: false,
			       url: url,
			       success: function() {
						$('.bgwb:first').addClass('isFmed');
						// 如果已经存在封面,就不需要再要默认封面
						if (saveFmIdChange == 0) {
							$('.bgwb:first').css({'background-image': 'url(' + url + ')'});
						}
						// 向数据库储存视频ID 和 封面ID
						$('#jinduwb').html('上传完成100%');
						$('#jinduwb').css({'z-index': '3'});
						$('#jindu').css({'width': '100%' ,'z-index': '2'});	
						// 有问题 PPVD还是需要检测
						setTimeout(function(){
							if (saveFmIdChange == 0) {
								setSaveFm(tempVideoId);
							}
							setSaveVideo(tempVideoId);
						}, 100);
						clearInterval(setPingTime);
			       },
			       error: function() {
			       }
			   });
		}, 1000);
	}
	
	// 用户自定义选择封面图片
	function setSaveFmSelf(tempVideoId, url) {
		saveFmIdChange = 1;
		$.ajax({
			url: requestUrl + '/user/upload/create',
			type: "post",
			dataType: "json",
			headers: {
				"Authorization": token
			},
			data: {
				"ppvod_image_id": tempVideoId,
				"type": 3
			},
			success: function(r) {
				saveFmIdChange = 0;
				$('.bgwb:first').addClass('isFmed');
				$('.bgwb:first').css({'background-image': 'url(' + url + ')'});
				saveFmId = r.data.id;
			},
			error: function(e) {
			}
		});
	}
	
	// 查看运转吗是否完成
	function checkPPODOver(tempVideoId) {
		var setPingTime1 = null;
		clearInterval(setPingTime1);
		setPingTime1 = setInterval(function(){
			$.ajax({
			       type: "GET",
			       url: requestUrl + '/user/ppvod/index',
				   dataType: 'json',
				   headers: {
				   	'Authorization': token
				   },
				   data: {
					   id: tempVideoId
				   },
			       success: function(r) {
						if (r.status == 0) {
							$('#jinduwb').html('上传完成100%');
							$('#jindu').css({'width': '100%' });
							setSaveFm(tempVideoId);
							setSaveVideo(tempVideoId);
							clearInterval(setPingTime);
						} else {
							// 在这里做进度处理
							var random = parseInt(Math.random() * 4) + 1;
							tempJinDu += random;
							if (tempJinDu >= 100) {
								tempJinDu = 99;
							}
							$('#jinduwb').html('上传中' + (tempJinDu) + '%...');
							$('#jindu').css({'width': (tempJinDu) + '%' });
						}
			       },
			       error: function() {
			       }
			   });
		}, 2000);
	};
	
	splitAddressUrl();
	ServerUrl = request.imgUrl;
	requestUrl = request.address;
	token = request.token;
	
	
	var vue = new Vue({
	el: '#updatePage',
	data: {
		tempFmSrc: '',
		choiceFm: null,
		hotType: [],
		tempFmId: '',
		title: '',
		placeholder: '写标题并使用合适的类型，能让更多人看到喔~'
	},
  	mounted() {
		var self = this;
		self.getHotClssType();
		setTimeout(function(){
			$("body").children("div:last-child").css("z-index", "9");
		}, 500)
  	},
	methods:{
		choseFm(e) {
			var self = this;
			if (e.target.files[0].type.indexOf('image') < 0) {
				showDalogleInfo({text: '请选择图片', time: 2000});
				var fileFengMian = document.getElementById('filefm');
				fileFengMian = '';
				fileFengMian.outerHTML = fileFengMian.outerHTML;
				return
			}
			var fmd = new FormData();
			fmd.append('type', 3);
			fmd.append('file', e.target.files[0]);
			$.ajax({
				url: requestUrl + '/user/upload/create',
				type: 'post',
				dataType: 'json',
				contentType: false,
				processData: false,
				data: fmd,
				headers: {
					'Authorization': token
				},
				success: function(r) {
					if (r.status == 0) {
						self.tempFmSrc = r.data.path_text;
						self.choiceFm =  r.data.path_text;
						// 设置封面ID
						self.tempFmId = r.data.id;
						// 用户向数据库提交
						saveFmId = r.data.id;
					}
				},
				error: function(e) {
				}
			});
		},
		// 获取热门分类
		getHotClssType() {
			var self = this;
			$.ajax({
				url: requestUrl + '/user/tag/hot',
				type: 'get',
				dataType: 'json',
				headers: {
					'Authorization': token
				},
				success: function(r) {
					self.hotType = r.data
				},
				error: function(e) {
				}
			});
		},
		// 设置title
		setTitle(item) {
			var self = this;
			if (self.title.length > 55) {
				showDalogleInfo({text: '标题最多55个字符', time: 2000});
				return;
			}
			if (self.title == '') {
				if(!item.name) {
					self.title += '#' + item.name
				}else {
					self.title += '#' + item.name
				}
			} else {
				let reg = /#([^`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、 ]+)/gm
				if(self.title.match(reg) && self.title.match(reg).length>2) {
					showDalogleInfo({text: '最多三个标签', time: 2000});
					return
				} else {
					self.title += ' #' + item.name
				}
				// var index = self.title.indexOf('#');
				// var num = 0; 
				// while(index !== -1) {
				// 	num++; 
				// 	index = self.title.indexOf('#', index + 1); 
				// }
				// if (num < 3) {
				// 	self.title += '#' + item.name
				// } else {
				// 	showDalogleInfo({text: '最多三个标签', time: 2000});
				// 	return;
				// }
			}
		},
		
		// 清空相关数据
		clearJson(){
			// 清空相关数据
			var self = this;
			self.title = '';
			self.tempFmSrc = '';
			self.choiceFm = null;
			tempJinDu = 1;
			$('#showToast').empty();
			$('#showToast').text('+上传作品');
			$('.bgwb:first').removeClass('isFmed');
			$('.bgwb:first').css({'background-image': 'url()'});
			// 允许点击发布按钮
			$('#send').attr('disabled', true);
			$('#send').css({'background-color': '#1C1B2B', 'color': '#747384'});
		},
		
		// 发布视频
		sendVideo() {
			var self = this;
			if (self.title.length > 55) {
				showDalogleInfo({text: '最多55个字符', time: 2000});
				return;
			}
			let reg = /#([^`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘'，。、 ]+)/gm
			if(self.title.match(reg) && self.title.match(reg).length>3) {
				showDalogleInfo({text: '最多三个标签', time: 2000});
				return
			}
			
			let apiData = {
				"upload_work_id": saveVideoId,
				"upload_work_cover_id": saveFmId
			}
			if(self.title.trim() != '') {
				apiData.title = self.title
			}
			
			// 保存视频ID 和 封面ID
			$.ajax({
				url: requestUrl + '/user/user/work/create',
				type: 'post',
				dataType: 'json',
				headers: {
					'Authorization': token
				},
				data: apiData,
				success: function(r) {
					if (r.status == 0) {
						showDalogleInfo({text: '发布成功', time: 1000});
						self.clearJson();
						setTimeout(function() {
							window.location.reload();
						}, 1000);
					}
				},
				error: function(e) {
				}
			});
		},
	
		// 点击选择封面图片的 不允许传递 视频
		handlerFm() {
			var self = this;
			testTemp = 1;
		}
	}
  })
</script>

